/*
 * 文件名：StreamDataSendClient.java
 * 版权：亚信联创版权所有
 * 描述：TODO
 * 修改人：napo
 * 修改时间：2014-11-13
 * 修改内容：TODO
 */
package com.ailk.bigdata.etl.realstream.server.netty.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ailk.bigdata.etl.common.server.net.socket.ISocketClient;
import com.ailk.bigdata.etl.realstream.server.netty.handler.RealStreamDataEncode;
import com.ailk.bigdata.etl.realstream.server.netty.handler.StreamDataInitiativeSenderHandler;

/**
 * @description 数据发送主动推送模式
 * @author [xuwei3]
 * @version [版本号,2014-11-13]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class StreamDataInitiativeSendClient
{
	private static final Logger logger = LoggerFactory.getLogger(ISocketClient.class);
	private String host;
	private int port;

	public StreamDataInitiativeSendClient(String host, int port)
	{
		this.host = host;
		this.port = port;
	}

	public Channel run()
	{
		Channel channel = null;
		EventLoopGroup group = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();
		try
		{
			bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
					.option(ChannelOption.SO_RCVBUF, 1048576 * 2).handler(new ChannelInitializer<SocketChannel>()
					{
						@Override
						protected void initChannel(SocketChannel ch) throws Exception
						{
							ChannelPipeline pipeline = ch.pipeline();
							pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192 * 4, Delimiters.lineDelimiter()));
							pipeline.addLast("encoder", new RealStreamDataEncode());
							pipeline.addLast("decoder", new StringDecoder());
							pipeline.addLast("handler", new StreamDataInitiativeSenderHandler());
						}
					});
			channel = bootstrap.connect(host, port).sync().channel();
		}
		catch (Exception e)
		{
			logger.error("连接失败！请确认host[" + host + "],port[" + port + "]是否配置正确", e);
		}
		return channel;
	}

}
